package com.ygqh.baby.service.task;

import com.foxinmy.weixin4j.mp.message.TemplateMessage;
import com.ygqh.baby.ao.CommentType;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.RefundStatus;
import com.ygqh.baby.ao.WxMessageType;
import com.ygqh.baby.model.wdt.qyb.PushOrderErrorInfo;
import com.ygqh.baby.model.wdt.qyb.WdtQybResult;
import com.ygqh.baby.po.*;
import com.ygqh.baby.service.*;
import com.ygqh.baby.service.wdtqyb.api.WdtQybApi;
import com.ygqh.baby.service.wdtqyb.api.WdtQybPushOrderByDetailApi;
import com.ygqh.baby.service.wdtqyb.exception.WdtException;
import com.ygqh.baby.utils.MailUtil;
import com.ygqh.baby.utils.YgStringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class YgAsynServer {
    protected final Logger logger = Logger.getLogger(this.getClass());
    @Autowired
    private WdtService wdtService;
    @Autowired
    private WdtQybApi wdtQybApi;
    @Autowired
    private WdtQybPushOrderByDetailApi wdtQybPushOrderByDetailApi;
    @Autowired
    private YgOrderLogService ygOrderLogService;
    @Autowired
    private YgOrderService ygOrderService;
    @Autowired
    private WxMpMessageService wxMpMessageService;
    @Autowired
    private WxMpAuthorityService wxMpAuthorityService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private YgUserService ygUserService;
    @Autowired
    private YgPublishService ygPublishService;
    @Autowired
    private YgMessageService ygMessageService;
    @Autowired
    private YgPublishCommentService ygPublishCommentService;
    @Autowired
    private AdminPurchaseService adminPurchaseService;
    @Autowired
    private YgReturnOrderService ygReturnOrderService;
    @Autowired
    private YgOrderDetailService ygOrderDetailService;
    @Autowired
    private YgReturnOrderDetailService ygReturnOrderDetailService;
    @Value("${promotion.link}")
    protected String promotionLink;

    @Value("${mail.to.cw}")
    protected String sendCwMail;

    @Autowired
    private MailUtil mailUtil;

    public void syncOrder(YgAsynCallBack ygAsynClient, List<Long> orderIds) {
        logger.debug("服务端：服务端接收到客户端发送的订单id为:" + orderIds.toString());
        // 模拟服务端需要对数据处理
        Message msg = wdtService.createOrderByOrderIds(orderIds);
        List<PushOrderErrorInfo> error = null;
        if (msg.getType().equals(Message.Type.error)) {
            error = (List<PushOrderErrorInfo>) msg.getExtra();
        }
        logger.debug("服务端:数据处理成功，返回成功状态 200");
        ygAsynClient.syncOrderCallBack(error);

    }

    public void syncQybOrder(YgAsynCallBack ygAsynClient, List<Long> orderIds) {
        logger.debug("服务端：服务端接收到客户端发送的订单id为:" + orderIds.toString());
        // 模拟服务端需要对数据处理
        Message msg = wdtQybApi.tradePushByOrderIds(orderIds);
        List<PushOrderErrorInfo> error = null;
        if (msg.getType().equals(Message.Type.error)) {
            error = (List<PushOrderErrorInfo>) msg.getExtra();
        }
        logger.debug("服务端:数据处理成功，返回成功状态 200");
        ygAsynClient.syncOrderCallBack(error);

    }

    public void sendWxMsg(YgAsynClient ygAsynClient, List<Long> orderIds, WxMessageType msgType) {
        logger.debug("服务端：服务端接收到客户端发送的订单id为:" + orderIds.toString());

        for (Long orderId : orderIds) {
            YgOrder order = ygOrderService.findOrderDetailByOrderId(orderId);
            if (order == null) {
                logger.warn("【sendWxMsg】 : 本地系统没有订单编号为：" + orderId + "的订单" + "msgType:" + msgType);
                continue;
            }
            YgUser user = ygUserService.findById(order.getUserId());
            // 商品已发送待接收
            if (msgType.equals(WxMessageType.WaitingSign)) {
                if (user.getOpenId() != null) {
                    TemplateMessage tplMessage = wxMpMessageService.getTemplateMessageInfo(order, user,
                            WxMessageType.WaitingSign);

                    Message message = wxMpMessageService.sendTemplateMessage(tplMessage);
                    if (message.getType().equals(Message.Type.error)) {

                        logger.warn("发送微信消息失败....msgType:" + msgType + ";订单编号:" + order.getOrderId());
                    }
                }
                // 发送手机短信
                if (YgStringUtils.isChinaPhoneLegal(user.getUserName())) {
                    String url = promotionLink + "/user/orderdetail.html?orderId=" + order.getOrderId();
                    String content = "亲，您的订单已经发货，请注意查收.";
                    logger.debug("发送订单商品已发出手机消息....订单编号:" + order.getOrderId());
                    smsService.sendSms(user.getUserName(), content);
                }

            }
            // 订单交易成功
            if (msgType.equals(WxMessageType.TradeSuccess)) {
                if (user.getOpenId() != null) {
                    TemplateMessage tplMessage = wxMpMessageService.getTemplateMessageInfo(order, user, msgType);
                    Message message = wxMpMessageService.sendTemplateMessage(tplMessage);
                    if (message.getType().equals(Message.Type.error)) {
                        logger.warn("【订单交易成功服务】：发送微信消息失败....msgType:" + msgType + ";订单编号:" + order.getOrderId());
                    }
                }

                // 发送手机短信
                if (YgStringUtils.isChinaPhoneLegal(user.getUserName())) {

                    String url = promotionLink + "/user/orderdetail.html?orderId=" + order.getOrderId();
                    String content = "亲，快去壹果评价吧，评价完成后您将收到1张优惠券！马上去评价吧！";
                    logger.debug("【订单交易成功服务】:手机消息....订单编号:" + order.getOrderId());
                    smsService.sendSms(user.getUserName(), content);
                }
            }
        }
        logger.debug("服务端:数据处理成功，返回成功状态 200");
        ygAsynClient.sendWxMsgCallBack(true);
    }

    public void syncPurchaseOrder(YgAsynClient ygAsynClient, AdminPurchase purchaseOrder) {
        logger.debug("服务端：服务端接收到客户端发送的采购单数据为:" + purchaseOrder.toString());
        wdtService.createStockInOrder(purchaseOrder);
        ygAsynClient.syncPurchaseOrderCallBack(true);
    }

    public void syncQybPurchaseOrder(YgAsynClient ygAsynClient, AdminPurchase purchaseOrder) {
        logger.debug("服务端：服务端接收到客户端发送的采购单数据为:" + purchaseOrder.toString());
        try {
            WdtQybResult result = wdtQybApi.purchasePush(purchaseOrder);
            adminPurchaseService.writeBackWdtPurchaseCode(purchaseOrder.getPurchaseCode(), result.getMessage());
            ygAsynClient.syncPurchaseOrderCallBack(true);
        } catch (WdtException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param ygAsynClient
     * @param publishId    被评论的晒单
     * @param userId       评论人Id
     * @param userId       评论人昵称
     * @param commentType
     */
    public void sendNewReviewMsg(YgAsynClient ygAsynClient, Long publishId, Long userId, String nickName,
                                 CommentType commentType) {
        YgPublish publish = ygPublishService.findById(publishId);
        List<YgPublishComment> list = ygPublishCommentService.findByPublishId(publishId);
        List<YgPublishComment> commentList = list.stream()
                .filter(item -> item.getPublishType().equals(CommentType.Comment)).collect(Collectors.toList());
        List<YgPublishComment> praiseList = list.stream()
                .filter(item -> item.getPublishType().equals(CommentType.Praise)).collect(Collectors.toList());
        if (commentType.equals(CommentType.Comment)) {
            // 发送给晒单用户
            if (!publish.getUserId().equals(userId)) {

                wxMpMessageService.sendNewReviewMsg("亲，有人评论了您的壹果晒单。", nickName, publish.getUserId(), publishId);
            }
            // 发给其他用户
            for (YgPublishComment comment : commentList) {
                if (!comment.getUserId().equals(userId) && !comment.getUserId().equals(publish.getUserId())) {
                    wxMpMessageService.sendNewReviewMsg("亲，有人和您评论了同一个壹果晒单，快去围观吧。", nickName, comment.getUserId(),
                            publishId);
                }
            }

        } else {
            // 发送给晒单用户
            if (!publish.getUserId().equals(userId)) {
                wxMpMessageService.sendNewReviewMsg("亲，有人赞了您的壹果晒单。", nickName, publish.getUserId(), publishId);
            }
            // 发给其他用户
            for (YgPublishComment praise : praiseList) {
                if (!praise.getUserId().equals(userId) && !praise.getUserId().equals(publish.getUserId())) {
                    wxMpMessageService.sendNewReviewMsg("亲，有人和您赞了同一个壹果晒单，快去围观吧。", nickName, praise.getUserId(),
                            publishId);
                }
            }
        }

    }

    public void sendInviteRegisterSuccessMsg(YgAsynClient ygAsynClient, String operId, String inviterSourceCode,
                                             String registerUserName, String registerNickName) {
        wxMpMessageService.sendInviteRegisterSuccessMsg(operId, inviterSourceCode, registerUserName, registerNickName);
    }

    public void syncCommissionDetail(YgAsynCallBack ygAsynClient, String commissionCode) {
        try {
            mailUtil.sendWithHtml(sendCwMail.split(","), "有新的申请单，申请单编码【" + commissionCode + "】", "");
        } catch (Exception e) {

        }
        logger.debug("服务端:数据处理成功，返回成功状态 200");
        ygAsynClient.syncCommissionDetailCallBack(true);
    }

    public void applyRefundOrder(YgAsynClient ygAsynClient, String returnCode, Boolean isSend) {
        WdtQybResult applyRefundResult = null;
        WdtQybResult pushChangeResult = null;

        String error = "";
        try {

            YgReturnOrder returnOrder = ygReturnOrderService.findDetailByReCode(returnCode);


            applyRefundResult = wdtQybApi.applyRefund(returnOrder, isSend);
            pushChangeResult = wdtQybApi.pushChangeOrderBefore(returnOrder, isSend);

            YgReturnOrder ygReturnOrder = new YgReturnOrder();
            ygReturnOrder.setId(returnOrder.getId());
            ygReturnOrder.setWdtOrderCode("QYB" + returnOrder.getReturnCode());
            ygReturnOrderService.update(ygReturnOrder);

            List<Long> collect = returnOrder.getReturnOrderDetails().stream().map(d -> d.getSourceSkuId())
                    .collect(Collectors.toList());
            RefundStatus refundStatus = RefundStatus.ApplyRefund;
//			if (!isSend && returnOrder.getReturnType().equals(ReturnType.Change)) {
//				refundStatus = RefundStatus.RefundSuccess;
//			}

            ygOrderDetailService.updateRefundStatusByReturn(returnOrder.getOrderId(), refundStatus, collect);

        } catch (Exception e) {
            error = e.getMessage();
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        ygAsynClient.applyRefundOrderBack(applyRefundResult, pushChangeResult, error, returnCode);
    }
}
